package pipecleaner.agent.core;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

public class ClasspathPropertyFileConfiguration implements Configuration
{	
	private static final String DEFAULT_PROPERTY_FILE = "agent-config.properties";

	private Map<String, Command> mapping;
	
	public ClasspathPropertyFileConfiguration () throws FileNotFoundException {
		loadConfiguration(DEFAULT_PROPERTY_FILE );
	}

	public Command loadCommand (HttpServletRequest request) {
		return mapping.get(request.getPathInfo());
	}

	public void setMapping (Map<String, Command> mapping) {
		this.mapping = mapping;
	}

	private void loadConfiguration (String fileName) throws FileNotFoundException {
		this.mapping = new HashMap<String, Command>();
		try {
			ClassLoader loader = this.getClass().getClassLoader(); 
			InputStream file = loader.getResourceAsStream(DEFAULT_PROPERTY_FILE);
			Properties props = new Properties();
			props.load(file);
			buildMapping(props);
		} catch (Exception e) {
			throw new FileNotFoundException("Unable to locate the properties configuration file.");
		}
	}

	private void buildMapping (Properties props) {
		for (Object key : props.keySet()) {
			if (key != null) {
				Command command = new ExecutableCommand((String)key, (String)props.get(key));
				this.mapping.put(command.getName(), command);
			}
		}
	}
}
